package com.bosssoft.login.controller;

import com.bosssoft.base.entity.Result;
import com.bosssoft.base.enums.ResultCodeEnum;
import com.bosssoft.login.entity.dto.UserDTO;
import com.bosssoft.login.entity.vo.UserInfoVO;
import com.bosssoft.login.entity.vo.UserVO;
import com.bosssoft.login.service.IUserService;
import com.bosssoft.login.utils.JwtUtil;
import com.bosssoft.login.utils.RsaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.Base64Utils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import com.bosssoft.base.util.VerifyCodeUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

@RestController
public class UserController {

    @Autowired
    private IUserService iUserService;

    private String imageCode = "";

    @Value("${salt.value}")
    private String value;

    //    获取公钥
    @GetMapping("/getPublicKey")
    public Result getPublicKey() {
        String publicKey = RsaUtil.getPublicKey();
        return Result.build(ResultCodeEnum.SUCCESS.getCode(), "获取公钥成功", publicKey);
//        return publicKey;
    }

    @GetMapping("/user/getImage")
    @ResponseBody
    public Result getImageCode() throws IOException {
//        JSONObject jsonObject = new JSONObject();
//        生成验证码
        String code = VerifyCodeUtils.generateVerifyCode(4);
        imageCode = code;
//        将图片转为 base64
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        VerifyCodeUtils.outputImage(220,60,byteArrayOutputStream,code);
        String base64 = "data:image/png;base64," + Base64Utils.encodeToString(byteArrayOutputStream.toByteArray());
//        jsonObject.put("base64",s);
        return Result.build(ResultCodeEnum.SUCCESS.getCode(), "获取成功", base64);
//        return JSONObject.toJSONString(jsonObject);
    }


    @PostMapping("/admin/login")
    public Result adminLogin(UserVO userVO) {
//        JSONObject jsonObject = new JSONObject();
        // 使用私钥进行解密,并加盐值
        String pwd = RsaUtil.decrypt(userVO.getPassword()) + value;
        String pwdMD5 = DigestUtils.md5DigestAsHex(pwd.getBytes());
        // 转为DTO
        UserDTO userDTO = new UserDTO();
        userDTO.setUsername(userVO.getUsername());
        userDTO.setPassword(userVO.getPassword());
        userDTO.setPhone(null);
        try{
            // 获取结果
            UserDTO resultUserDTO = iUserService.getUserByUserName(userDTO);
            if(resultUserDTO != null) {
                UserVO newUserVO = new UserVO(resultUserDTO.getUsername(), resultUserDTO.getPassword(), resultUserDTO.getPhone(), resultUserDTO.getUid());
                if (pwdMD5.equals(newUserVO.getPassword())) {
                    String s = Integer.toString(resultUserDTO.getUid());
                    String username = resultUserDTO.getUsername();
                    String token = JwtUtil.createJwtToken(s, username);
                    // 获取成功，创建token
                    UserInfoVO userInfoVO = new UserInfoVO(newUserVO.getUsername(), newUserVO.getPhone(), newUserVO.getUid(), token);
//                    jsonObject.put("code", 200);
//                    jsonObject.put("data", userInfoVO);
//                    return JSONObject.toJSONString(jsonObject);
                    return Result.build(ResultCodeEnum.SUCCESS.getCode(), "登录成功", userInfoVO);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
//        jsonObject.put("code", 202);
//        jsonObject.put("message", "登录失败");
//        return JSONObject.toJSONString(jsonObject);
        return Result.build(ResultCodeEnum.USERNAME_PASSWORD_ERROR.getCode(),"用户名或密码错误",null);
    }


    @PostMapping("/user/login")
    public Result userLogin(UserVO userVO,String imageCode) {

//        imageCode = imageCode.toUpperCase();
//        JSONObject jsonObject = new JSONObject();
        if(!this.imageCode.equals(imageCode.toUpperCase())){
//            jsonObject.put("code",60002);
//            jsonObject.put("data","验证码错误");
//            return JSONObject.toJSONString(jsonObject);
            return Result.build(ResultCodeEnum.IMAGE_CODE.getCode(),"验证码错误",null);
        }

//        JSONObject jsonObject = new JSONObject();
        // 使用私钥进行解密,并加盐值
        String pwd = RsaUtil.decrypt(userVO.getPassword()) + value;
        String pwdMD5 = DigestUtils.md5DigestAsHex(pwd.getBytes());
        // 转为DTO
        UserDTO userDTO = new UserDTO();
        userDTO.setUsername(userVO.getUsername());
        userDTO.setPassword(userVO.getPassword());
        userDTO.setPhone(null);
        try{
            // 获取结果
            UserDTO resultUserDTO = iUserService.getUserByUserName(userDTO);
            if(resultUserDTO != null) {
                UserVO newUserVO = new UserVO(resultUserDTO.getUsername(), resultUserDTO.getPassword(), resultUserDTO.getPhone(), resultUserDTO.getUid());
                if (pwdMD5.equals(newUserVO.getPassword())) {
                    String s = Integer.toString(resultUserDTO.getUid());
                    String username = resultUserDTO.getUsername();
                    String token = JwtUtil.createJwtToken(s, username);
                    // 获取成功，创建token
                    UserInfoVO userInfoVO = new UserInfoVO(newUserVO.getUsername(), newUserVO.getPhone(), newUserVO.getUid(), token);
//                    jsonObject.put("code", 200);
//                    jsonObject.put("data", userInfoVO);
                    return Result.build(ResultCodeEnum.SUCCESS.getCode(), "登录成功", userInfoVO);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
//        jsonObject.put("code", 202);
//        jsonObject.put("message", "登录失败");
//        return JSONObject.toJSONString(jsonObject);
        return Result.build(ResultCodeEnum.USERNAME_PASSWORD_ERROR.getCode(),"用户名或密码错误",null);
    }

    @PostMapping("/user/signUp")
    public Result insertUser(UserVO userVO) {
//        JSONObject jsonObject = new JSONObject();
        if (userVO.getPassword() == null || userVO.getUsername() == null) {
//            jsonObject.put("code", 400);
//            jsonObject.put("message", "创建失败");
            return Result.build(ResultCodeEnum.PARAM_NOT_NULL.getCode(),"用户名或密码不能为空",null);
        }
        // 转为DTO
        UserDTO userDTO = new UserDTO();
        userDTO.setUsername(userVO.getUsername());
        userDTO.setPassword(userVO.getPassword());
        userDTO.setPhone(userVO.getPhone());
//        iUserService.getUser(userDTO);
        if (iUserService.getUser(userDTO)) {
//            jsonObject.put("code", 201);
//            jsonObject.put("message", "用户名已存在");
//            return JSONObject.toJSONString(jsonObject);
            return Result.build(ResultCodeEnum.ERROR.getCode(),"用户名已存在",null);
        }
        //解密加盐再MD5加密
        String pwd = DigestUtils.md5DigestAsHex((RsaUtil.decrypt(userDTO.getPassword()) + value).getBytes());
        userDTO.setPassword(pwd);
        Integer result = iUserService.insertUser(userDTO);
        if (result == 1) {
//            jsonObject.put("code", 200);
//            jsonObject.put("message", "创建成功");
            return Result.build(ResultCodeEnum.SUCCESS.getCode(),"创建成功",null);
        } else {
//            jsonObject.put("code", 400);
//            jsonObject.put("message", "创建失败");
            return Result.build(ResultCodeEnum.ERROR.getCode(),"创建失败",null);
        }
//        return JSONObject.toJSONString(jsonObject);
    }
}
